<template>
  <div>
    <div class="bg-wrap">
      <img :src="themeImg" mode="widthFix" class="bg-img" />
      <!-- <button
        class="btn-round-blue"
        :disabled="!hasQR"
        @click="handleSaveImg"
      >保存图片</button>-->

      <div class="qr-wrap">
        <div class="hint">
          <img
            src="https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/wallet_qr_code.png"
            mode="widthFix"
          />
          <span>二维码收款</span>
        </div>
        <div v-if="!hasQR" class="tip">
          您还没有线下收款二维码
          <br />快一键生成一个吧！
        </div>
        <img v-else :src="qrURL" mode="aspectFit" class="qr" />
        <span class="saveText" @click="handleSaveImg">保存收款码</span>
        <!-- <button class="btn-color-blue" @click="changeLogo">{{btnText}}</button> -->
      </div>
    </div>
  </div>
</template>

<script>
import { base64ToSrc } from '@/utils'
import {
  FIND_SHOP_BASE_INFO,
  FIND_SHOP_URL,
  UPDATE_SHOP_QR_LOGO,
  UPLOAD_IMAGE,
  UPDATE_SHOP_BASE_INFO,
  NEW_GENERATE_SHOP_URL
} from '@/api'

export default {
  components: {},
  props: {},
  data () {
    return {
      auth: {},
      qrURL: '',
      shopURL: '',
      generateState: false
    }
  },
  computed: {
    hasQR () {
      return !!this.qrURL
    },
    btnText () {
      if (this.hasQR) {
        return '更换LOGO'
      } else {
        return '生成店铺收款二维码'
      }
    },
    themeImg () {
      let appId = this.$store.state.appId
      if (appId !== 'wx657f1b2fb50b5be3') {
        return 'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/bg_receipt_qr_code.png'
      } else {
        return 'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/bg_receipt_qr_code2.png'
      }
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.getAuth()
    this.findQRCode()
  },
  methods: {
    /**
     * 1.拿到logo
     * 2.拿到店铺链接
     * 3.默认下载二维码
     * 4.生成新的二维码
     *  **/
    handleSaveImg () {
      const vm = this
      let url = vm.qrURL
      if (vm.auth && vm.auth['scope.writePhotosAlbum'] !== false) {
        wx.saveImageToPhotosAlbum({
          filePath: url,
          success: function (res) {
            vm.$toast('操作成功')
          },
          fail: function (err) {
            console.error(err)
            vm.getAuth()
          }
        })
      } else {
        wx.openSetting({
          success: function (res) {
            console.info(res)
          },
          fail: function (err) {
            console.error(err)
          }
        })
        vm.$toast('需要授权后才能继续')
      }
    }, // 点击保存二维码

    getAuth () {
      const vm = this
      wx.getSetting({
        success: function (res) {
          vm.auth = res.authSetting
        },
        fail: function (err) {
          console.error(err)
        }
      })
    }, // 获取用户当前设置
    findQRCode () {
      const vm = this
      vm.qrURL = ''
      FIND_SHOP_BASE_INFO(vm.$store.state.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            let { offlineQrCode, logo } = r.data.data
            vm.qrURL = offlineQrCode
            if (logo) {
              if (logo.indexOf('https') === -1 && logo.indexOf('http') !== -1) {
                vm.logoUrl = logo.replace('http', 'https')
              } else {
                vm.logoUrl = logo
              }
            } else {
              vm.logoUrl = logo
            }
            vm.findShopURL() // 生成小链接
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 拿到店铺logo
    findShopURL () {
      const vm = this
      let params = {
        shopId: vm.$store.state.account.shopId,
        isOffline: true
      }
      FIND_SHOP_URL(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.shopURL = r.data.data
            vm.generateState = true
            vm.test()
            if (r.data.data === '无') {
              vm.isFindOneCode()
            }
          } else if (r.data.code === '-1') {
            vm.isFindOneCode()
          } else {
            vm.test()
            vm.generateState = false
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 查询店铺小链接
    isFindOneCode () {
      const vm = this
      NEW_GENERATE_SHOP_URL(vm.$store.state.account.shopId, true)
        .then(r => {
          if (r.data.code === '0' && r.data.data) {
            vm.shopURL = r.data.data
            vm.test()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 生成店铺小链接
    test () {
      const vm = this
      vm.$loading.show()
      if (vm.logoUrl) {
        wx.downloadFile({
          url: vm.logoUrl,
          success (res) {
            if (res.statusCode === 200) {
              vm.getQRLogo(res.tempFilePath)
            }
            vm.$loading.close()
          },
          fail: function (err) {
            console.error(err)
            vm.$loading.close()
          }
        })
      } else {
        vm.$loading.close()
        vm.$alert('请先前往店铺配置，生成店铺logo').then(r => {
          vm.$router.go(-1)
        })
      }
    }, // 默认下载二维码
    getQRLogo (res) {
      const vm = this
      vm.$loading.show()
      wx.uploadFile({
        url: `https://akk.028wkf.cn/gateway/store-platform/qrCode/buildQRCode?url=${
          vm.shopURL
        }`,
        filePath: res,
        name: 'logo',
        header: {
          'Content-Type': 'multipart/form-data',
          Accept: 'application/json',
          Cookie: vm.$cookie.get('my-cookie')
        },
        formData: {
          logo: res
        },
        success: function (re) {
          base64ToSrc('data:image/png;base64,' + JSON.parse(re.data).data)
            .then(r => {
              vm.qrURL = r
            })
            .catch(e => {
              console.error(e)
            })
          vm.$loading.close()
        },
        fail: function (err) {
          console.error(err)
          vm.$loading.close()
        }
      })
    },
    changeLogo () {
      const vm = this
      if (vm.generateState) {
        UPDATE_SHOP_QR_LOGO(vm.shopURL)
          .then(r => {
            let res = JSON.parse(r.data)
            if (res.code === '0') {
              base64ToSrc('data:image/png;base64,' + res.data)
                .then(r => {
                  vm.uploadNewQR(r)
                })
                .catch(e => {
                  console.error(e)
                })
            } else {
              vm.$toast(res.message)
            }
          })
          .catch(e => {
            console.error(e)
          })
      } else {
        vm.$toast('请先去生成店铺小链接')
      }
    }, // 暂时没用的
    uploadNewQR (filePath) {
      const vm = this
      vm.qrURL = ''
      UPLOAD_IMAGE(filePath)
        .then(r => {
          let res = JSON.parse(r.data)
          if (res.code === '0') {
            vm.qrURL = res.data.imgPath
            vm.updateShopInfo()
          } else {
            vm.$toast(res.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 暂时没用的
    updateShopInfo () {
      const vm = this

      let params = {
        shopId: vm.$store.state.account.shopId,
        offlineQrCode: vm.qrURL
      }

      UPDATE_SHOP_BASE_INFO(params)
        .then(r => {
          if (r.data.code === '0' && r.data.data) {
            vm.$toast('操作成功')
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    } // 暂时没用的
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';
.bg-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  > .bg-img {
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    z-index: -1;
  }
  > .btn-round-blue {
    width: 40%;
    margin-bottom: 20px;
  }
  > .qr-wrap {
    position: absolute;
    background-color: $white;
    // width: calc(100% - 120px);
    width: calc(100% - 20px);
    top: 60px;
    left: 50%;
    transform: translate(-50%, 0%);
    border-radius: 6px;
    padding: 50px 30px 70px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .hint {
      display: flex;
      align-items: center;
      position: absolute;
      top: 8px;
      left: 13px;
      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
      span {
        font-size: 15px;
        color: #d5bc77;
      }
    }
    > .tip {
      height: 130px;
      text-align: center;
      color: $red;
      font-size: 15px;
      line-height: 200%;
    }
    > .qr {
      width: 230px;
      height: 230px;
    }
    > .btn-color-blue {
      margin-top: 30px;
    }
    > .saveText {
      font-size: 16px;
      color: #677084;
      margin: 35px 0;
    }
  }
}
</style>
